<?php
session_start();

function Obtener_Conexion(){
	require("morsa.inc"); 
	$conexion=pg_connect("host=$DB_SERVER dbname=$DB user=$DB_LOGIN password=$DB_PASS") or die ("No pudo conectar con $DB en $DB_SERVER "  );
	return $conexion ;
}

function Desconectar($conexion){
	pg_close($conexion);
}

$conexion=Obtener_Conexion();
$sql=" select distinct p.num_prov, p.nom_prov from invprov p, swpr_vlineas l where p.num_prov=l.num_prov order by nom_prov ";
$res=pg_query($conexion,$sql)  or die ("Error $sql ");
$total=pg_num_rows($res);

$aClientes = array();

while ($reg=pg_fetch_array($res)){
	$aClientes[] = array( "numcte"=>($reg[0]) ,"nombre"=>htmlspecialchars($reg[1]) );
}

Desconectar($conexion);
	
	$input = strtolower( $_GET['input'] );
	$len = strlen($input);
	
	$aResults = array();
	
	if ($len)
	{
		for ($i=0;$i<count($aClientes);$i++)
		{
			// had to use utf_decode, here
			// not necessary if the results are coming from mysql
			//

			if (strtolower(substr(utf8_decode($aClientes[$i]['nombre']),0,$len)) == $input)
				$aResults[] = array( "id"=>($aClientes[$i]['numcte']) ,"value"=>($aClientes[$i]['nombre']), "info"=>($i+1) );
			
		}
	}
	
		
	
	
	
	
	
	
	header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
	header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
	header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
	header ("Pragma: no-cache"); // HTTP/1.0
	
	
	
	if (isset($_REQUEST['json']))
	{
		header("Content-Type: application/json");
	
		echo "{\"results\": [";
		$arr = array();
		for ($i=0;$i<count($aResults);$i++)
		{
			$arr[] = "{\"id\": \"".$aResults[$i]['id']."\", \"value\": \"".$aResults[$i]['value']."\", \"info\": \"\"}";
		}
		echo implode(", ", $arr);
		echo "]}";
	}
	else
	{
		header("Content-Type: text/xml");

		echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?><results>";
		for ($i=0;$i<count($aResults);$i++)
		{
			echo "<rs id=\"".$aResults[$i]['id']."\" info=\"".$aResults[$i]['info']."\">".$aResults[$i]['value']."</rs>";
		}
		echo "</results>";
	}
?>